package com.example.sqliteviewer;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * JSON数据导出工具类
 */
public class JsonExportUtils {

    /**
     * 将表数据导出为JSON文件
     *
     * @param context      上下文
     * @param databasePath 数据库路径
     * @param tableName    表名
     * @param searchQuery  搜索条件（可为空）
     * @return 导出的文件路径，如果导出失败则返回null
     */
    public static String exportTableToJSON(Context context, String databasePath, String tableName, String searchQuery) {
        SQLiteDatabase database = null;
        Cursor cursor = null;
        FileWriter fileWriter = null;
        
        try {
            // 打开数据库
            database = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READONLY);
            
            // 获取表结构
            Cursor structureCursor = database.rawQuery("PRAGMA table_info(" + tableName + ")", null);
            
            if (!structureCursor.moveToFirst()) {
                Toast.makeText(context, "无法获取表结构", Toast.LENGTH_SHORT).show();
                structureCursor.close();
                return null;
            }
            
            // 获取列名
            int columnCount = structureCursor.getCount();
            String[] columnNames = new String[columnCount];
            int index = 0;
            
            do {
                String columnName = structureCursor.getString(structureCursor.getColumnIndex("name"));
                columnNames[index++] = columnName;
            } while (structureCursor.moveToNext());
            
            structureCursor.close();
            
            // 构建查询语句
            StringBuilder queryBuilder = new StringBuilder();
            queryBuilder.append("SELECT * FROM ").append(tableName);
            
            // 如果有搜索条件，添加WHERE子句
            if (searchQuery != null && !searchQuery.isEmpty()) {
                queryBuilder.append(" WHERE ");
                
                for (int i = 0; i < columnNames.length; i++) {
                    if (i > 0) {
                        queryBuilder.append(" OR ");
                    }
                    queryBuilder.append(columnNames[i]).append(" LIKE '%").append(searchQuery).append("%'");
                }
            }
            
            // 执行查询
            cursor = database.rawQuery(queryBuilder.toString(), null);
            
            if (cursor.getCount() == 0) {
                Toast.makeText(context, "没有数据可导出", Toast.LENGTH_SHORT).show();
                return null;
            }
            
            // 创建JSON数组存储所有行数据
            JSONArray jsonArray = new JSONArray();
            
            // 将数据转换为JSON对象
            if (cursor.moveToFirst()) {
                do {
                    JSONObject rowObject = new JSONObject();
                    
                    for (int i = 0; i < columnNames.length; i++) {
                        if (!cursor.isNull(i)) {
                            switch (cursor.getType(i)) {
                                case Cursor.FIELD_TYPE_INTEGER:
                                    rowObject.put(columnNames[i], cursor.getLong(i));
                                    break;
                                case Cursor.FIELD_TYPE_FLOAT:
                                    rowObject.put(columnNames[i], cursor.getDouble(i));
                                    break;
                                case Cursor.FIELD_TYPE_STRING:
                                    rowObject.put(columnNames[i], cursor.getString(i));
                                    break;
                                case Cursor.FIELD_TYPE_BLOB:
                                    rowObject.put(columnNames[i], "[BLOB]");
                                    break;
                                case Cursor.FIELD_TYPE_NULL:
                                    rowObject.put(columnNames[i], JSONObject.NULL);
                                    break;
                            }
                        } else {
                            rowObject.put(columnNames[i], JSONObject.NULL);
                        }
                    }
                    
                    jsonArray.put(rowObject);
                    
                } while (cursor.moveToNext());
            }
            
            // 创建导出目录
            File exportDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "SQLiteViewer");
            if (!exportDir.exists()) {
                exportDir.mkdirs();
            }
            
            // 创建导出文件
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
            String timestamp = dateFormat.format(new Date());
            String fileName = tableName + "_" + timestamp + ".json";
            File exportFile = new File(exportDir, fileName);
            
            fileWriter = new FileWriter(exportFile);
            fileWriter.write(jsonArray.toString(4)); // 使用4个空格缩进格式化JSON
            
            return exportFile.getAbsolutePath();
            
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(context, "导出失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            return null;
        } finally {
            // 关闭资源
            if (cursor != null) {
                cursor.close();
            }
            if (database != null) {
                database.close();
            }
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}